<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 左右布局,方式1-通过栅格布局 -->
        <!-- <el-row>
          <el-col :span="22">左</el-col>
          <el-col :span="2">右</el-col>
        </el-row> -->

        <tree-node :data="companyInfo">
          <el-dropdown-item :disabled="!hasPerm('add-dept')" @click.native="onAdd(companyInfo)">添加子部门</el-dropdown-item>
        </tree-node>
        <el-tree :data="list" :props="{label:'name'}" default-expand-al1>
          <template v-slot="{data}">
            <tree-node :data="data">
              <el-dropdown-item :disabled="!hasPerm('add-dept')" @click.native="onAdd(companyInfo)">添加子部门</el-dropdown-item>
              <el-dropdown-item @click.native="onUpdate(data.id)">编辑部门</el-dropdown-item>
              <el-dropdown-item @click.native="onDel(data.id)">删除部门</el-dropdown-item>
            </tree-node>
          </template>

        </el-tree>
      </el-card>
    </div>
    <add-dept ref="addRef" :show-dialog.sync="showDialog" :node="currentNode" @success="getDepartments"></add-dept>
  </div>
</template>

<script>
import { getDepartments, delDepartments, DepartmentsById } from '@/api/departments.js'
import { translateListToTree } from '../../utils/index.js'
import treeNode from './components/tree-node.vue'
import addDept from './components/add-dept.vue'
export default {
  name: 'DepartmentsPage',
  components: { treeNode, addDept },
  props: {},
  data() {
    return {
      currentNode: {}, // 当前操作的部门
      showDialog: false, // 控制对话弹窗显示
      companyInfo: { name: '传智教育', manager: '负责人', id: '' },
      list: []
    }
  },
  created() {
    this.getDepartments()
  },
  mounted() {},
  methods: {
    // 定义方法,判断是否有按钮权限
    // hasPerm(key) {
    //   return this.$store.state.user.userInfo.roles.points.includes(key)
    // },
    async getDepartments() {
      const { depts } = await getDepartments()
      this.list = translateListToTree(depts, '')
    },
    onAdd(node) {
      this.currentNode = node
      this.showDialog = true
    },
    async onUpdate(id) {
      // 获取详情
      const data = await DepartmentsById(id)
      console.log('data', data)
      this.$refs.addRef.form = data
      // 打开对话框
      this.showDialog = true
    },
    onDel(id) {
      // 确认删除
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        // 点击确定
        await delDepartments(id)
        // 提示成功
        this.$message.success('操作成功')
        // 刷新列表
        this.getDeparments
      }).catch(() => {

      })
    }
  }

}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}

</style>

